package com.example.beautyhub.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.beautyhub.model.User;
import com.example.beautyhub.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {
    
    @Autowired
    private UserService userService;

    @GetMapping("/")
    public List<User> list() {
        return userService.list();
    }

    @ApiOperation("分页查询")
    @GetMapping("/list")
    public Page<User> getUserList(int pageNum, int pageSize) {
        Page<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("type","user"); //根据条件查询
        return userService.page(page,wrapper);//返回分页数据
    }

    @ApiOperation("搜索")
    @GetMapping("/search")
    public List<User> getSearchList(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username",user.getUsername()); //根据条件查询
        return userService.list(wrapper);//返回分页数据
    }

    @GetMapping("/{id}")
    public User findById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @ApiOperation("登陆")
    @PostMapping("/login")
    public int login(User user) {
        // 获取前端传入的原始密码，并进行加密
        String userPassword = user.getPassword();
        // 使用 LambdaQueryWrapper 查询符合条件的加密后的密码
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        List<User> userList = userService.list(wrapper);
        // 对查询结果进行密码校验
        if (userList != null && userList.size() > 0) {
            String dbEncodedPassword = userList.get(0).getPassword();
            if (userPassword.equals(dbEncodedPassword)) {
                // 密码匹配
                if (userList.get(0).getType().equals("admin"))
                    return 1;
                else
                    return 0;
            } else {
                // 密码不匹配
                return -1;
            }
        } else {
            // 用户不存在
            return -2;
        }
    }

    @PostMapping("/")
    public void add(@RequestBody User user) {
        user.setPassword("123456");
        user.setCreatedate(new Date());
        userService.save(user);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable Integer id, @RequestBody User user) {
        user.setId(id);
        userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        userService.removeById(id);
    }
}

